package hackthon.core;


import java.io.*;

/**
 * Created by wuwenhao on 14/10/27.
 */
public class MySerializable implements Serializable {


//    public static void main(String args[]){
//        Employee emp = new Employee();
//        emp.setId(1);
//        emp.setManagerId(3);
//        emp.setName("wuwenhao");
//        emp.setPass("qwe");
//        byte b[] = null;
//        try {
//            b = serializable(emp);
//            System.out.println(b);
//            System.out.println(b.toString());
//            System.out.println(String.valueOf(b));
//            System.out.println(String.valueOf(b));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            Object obj = unSerializable(b);
//            if(obj instanceof Employee){
//                System.out.println(((Employee) obj).getName());
//            }
//            System.out.println();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public static byte[] serializable(Object obj) throws IOException {

        ObjectOutputStream objectOutputStream = null;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try{
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            return byteArrayOutputStream.toByteArray();
        }finally {
            objectOutputStream.flush();
            objectOutputStream.close();
        }
    }

    public static Object unSerializable(byte []bytes) throws IOException{
        if(bytes == null || bytes.length == 0){
            return null;
        }
        ObjectInputStream objectInputStream = null;
        try{
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            objectInputStream.close();
        }
        return null;
    }

}
